package com.example.online_forum.exception;

import com.example.online_forum.common.AppResult;
import com.example.online_forum.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局统一异常处理
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler  {
    @ResponseBody
    @ExceptionHandler(AppException.class)
    public AppResult applicationException(AppException e){
        //打印异常信息
        e.printStackTrace();
        //打印日志
        log.error(e.getMessage());
        if(e.getErrorResult() != null){
            return e.getErrorResult();
        }
        //返回具体的异常信息
        if(e.getMessage() == null || e.getMessage().isEmpty()){
            return AppResult.failed(ResultCode.ERROR_SERVICES + "applicationException1");
        }
        return AppResult.failed(e.getMessage());
    }
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public AppResult applicationException(Exception e){
        e.printStackTrace();
        //打印日志
        log.error(e.getMessage());
        //非空效验
        if(e.getMessage() == null || e.getMessage().isEmpty()){
            return AppResult.failed(ResultCode.ERROR_SERVICES + "applicationException2");
        }
        return AppResult.failed(e.getMessage());
    }
}
